package com.greendragon.persistence.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.greendragon.persistence.dao.IAlbumDao;
import com.greendragon.persistence.domain.Album;
import com.greendragon.persistence.domain.Resource;
import com.greendragon.persistence.enmu.FetchOrderType;

/**
 * @author wulibin, exceptsky@gmail.com, 2011-9-24 下午10:20:25
 * 
 */
@SuppressWarnings("unchecked")
public class AlbumDaoImpl extends BaseDao<Album> implements IAlbumDao {
	private static Logger          logger           = Logger.getLogger(AlbumDaoImpl.class);
	@Override
	public long getCountOfPhotos(long id) {
		String hql = "select count(a.photos) from Album as a where a.id = ?";
		try{
			List rs = getHibernateTemplate().find(hql, id);
			if(rs==null || rs.size()==0){
				return 0l;
			}
			long count = ((Long)rs.listIterator().next()).longValue();
			return count;
		}catch(Exception e){
			logger.error(e);
			return 0l;
		}
	}

	@Override
	public List<Resource> getCoversByPage(final int offset, final int length, final FetchOrderType orderType) {
		try{
			List<Resource> result = getHibernateTemplate().executeFind(
					new HibernateCallback() {
						public Object doInHibernate(Session session)
								throws HibernateException, SQLException {
							String hql = "select a.coverImg from Album as a "+ getOrderSql("a",orderType);
							Query query = session.createQuery(hql);
							query.setFirstResult(offset);
							query.setMaxResults(length);
							return query.list();
						}
					});
			return result;
		}catch (Exception e) {
			logger.error(e);
			return null;
		}
	
	}

	@Override
	public List<Resource> getPhotos(final long id, final int offset,
			final int length, final FetchOrderType orderType) {
		try{
			List<Resource> result = getHibernateTemplate().executeFind(
					new HibernateCallback() {
						public Object doInHibernate(Session session)
								throws HibernateException, SQLException {
							String hql = "select a.photos from Album as a where a.id = ?" + getOrderSql("a.photos",orderType);
							Query query = session.createQuery(hql);
							query.setLong(0, id);
							query.setFirstResult(offset);
							query.setMaxResults(length);
							return query.list();
						}
					});
			return result;
		}catch (Exception e) {
			logger.error(e);
			return null;
		}
	}

}
